﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
    public class MostPopularObjectTracker <TValue, TState> 
    {
        public class StatsTracker
        {
            public TValue Value { get; internal set; }
            internal int Votes { get; set; }
            public TState State { get; internal set; }
        }
        private object synclock = new object();

        private IDictionary<TValue, StatsTracker> lookup = new Dictionary<TValue, StatsTracker>();
        private IList<StatsTracker> allStats = new List<StatsTracker>();

        public void VoteUp(TValue obj, TState state)
        {
            lock (synclock)
            {
                StatsTracker st = null;
                if (!lookup.TryGetValue(obj, out st))
                {
                    st = new StatsTracker() { Value = obj, State = state };
                    lookup.Add(obj, st);
                    allStats.Add(st);
                }
                st.Votes++;
            }
        }

        public void PruneData(int numToKeep)
        {
            lock (synclock)
            {
                var keeping = MostPopular(numToKeep);
                allStats.Clear();
                lookup.Clear();
                foreach (var kept in keeping)
                {
                    VoteUp(kept.Value, kept.State);
                }
            }
        }

        public IEnumerable<StatsTracker> MostPopular(int numberToGrab)
        {
            lock (synclock)
            {
                return (from stat in allStats
                        orderby stat.Votes ascending
                        select stat).Take(numberToGrab).ToList();
            }
        }
    }
}
